const fs = require("fs");
let content = fs.readFileSync(__dirname + "/行政区域2007.txt", {
  encoding: "utf-8",
});

let areaArray = content
  .split("\n")
  .map((line) => line.trim())
  .filter((line) => line != "")
  .map((line) => {
    let area = line.split(/\s/);
    return {
      code: area[0].trim(),
      name: area[1].trim(),
    };
  });

let key = {};
for (const area of areaArray) {
  let code = area.code;
  try {
    if (code.substr(2, 4) == "0000") {
      key[code] = {
        name: area.name,
        code: code,
      };
    } else if (code.substr(4, 2) == "00") {
      let provinceCode = code.substr(0, 2) + "0000";
      let province = key[provinceCode];
      if (!province.children) {
        province.children = {};
      }
      let children = province.children;
      children[code] = {
        name: area.name,
        code: code,
      };
    } else {
      let provinceCode = code.substr(0, 2) + "0000";
      let cityCode = code.substr(0, 4) + "00";
      let province = key[provinceCode];
      let city = province[cityCode];
      if (!city) {
        city = province;
      }
      if (!city.children) {
        city.children = {};
      }
      let children = city.children;
      children[code] = {
        name: area.name,
        code: code,
      };
    }
  } catch (error) {
    console.log(code);
    console.log(key)
    throw error;
  }
}
fs.writeFileSync(__dirname + '/行政区域.json', JSON.stringify(key, null, 2))

